import collections


class Solution(object):
    def findLength(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: int
        """
        base = 10 ** 9 + 7
        n1 = len(nums1)
        n2 = len(nums2)
        left = 0
        right = min(n1, n2)

        def search(length):
            if length == 0:
                return True
            t1 = collections.defaultdict(set)
            t2 = collections.defaultdict(set)
            value1 = 0
            value2 = 0
            for i in range(length):
                value1 = (value1 * 10 + nums1[i]) % base
                value2 = (value2 * 10 + nums2[i]) % base
            t1[value1].add(0)
            t2[value2].add(0)
            for i in range(n1 - length):
                value1 = ((value1 - nums1[i] * pow(10, length - 1, base)) * 10 + nums1[i + length]) % base
                t1[value1].add(i + 1)
            for i in range(n2 - length):
                value2 = ((value2 - nums2[i] * pow(10, length - 1, base)) * 10 + nums2[i + length]) % base
                t2[value2].add(i + 1)
            for key in t1:
                if key in t2:
                    for x in t1[key]:
                        for y in t2[key]:
                            if nums1[x: x + length] == nums2[y: y + length]:
                                return True
            return False

        while left < right:
            mid = (left + right + 1) // 2
            if search(mid):
                left = mid
            else:
                right = mid - 1
        return left


data = Solution()
nums1 = [1, 2, 3, 2, 1]
nums2 = [3, 2, 1, 4, 7]
print(data.findLength(nums1, nums2))
nums1 = [0, 0, 0, 0, 0]
nums2 = [0, 0, 0, 0, 0]
print(data.findLength(nums1, nums2))
